from django.shortcuts import render,redirect,reverse
from  django.http import  HttpResponse
# Create your views here.
from  django.contrib.auth.models import  User
from  django.contrib.auth import  authenticate, login, logout
from django.views.generic import View
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired
from e_shop import  settings
import re
from django.core.mail import send_mail
from celery_tasks.tasks import send_active_email
from itsdangerous import TimedJSONWebSignatureSerializer as TJWSS


'''
def register(request):
    # 当请求方式为get时表示请求注册页面，反之为处理用户注册数据
    if request.method=='GET':
        '显示注册界面'
        return render(request,'register.html')
    else:
        # 接收注册表单数据
        username = request.POST.get("user_name")
        password = request.POST.get("pwd")
        email = request.POST.get("email")
        allow = request.POST.get("allow")
        # 判断用户传递过来的数据是否存在，不存在返回错误信息提示
        if not all([username, password, email]):
            return render(request, 'register.html', {'error_msg': '数据不完整'})
        # 判断用户填写的邮箱是否为正确邮箱
        if not re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", email):
            return render(request, 'register.html', {'error_msg': '邮箱格式不正确'})
        # 判断用户注册时是否勾选同意，同意后该字段POST请求参数为on
        if allow != 'on':
            return render(request, 'register.html', {'error_msg': '请勾选同意'})
        # user=User.objects._create_user(username,email,password)user=User.objects._create_user(username,email,password)
        # 在进行用户注册之前，需要判断用户注册的用户名是否存在
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            '如果出现该异常说明用户不存在,让user对象为空'
            user = None
        if user:
            return render(request, 'register.html', {'error_msg': '用户已存在'})
        return redirect(reverse('goods:index'))
def register_handle(request):
    '处理用户注册数据'
    # 接收注册表单数据
    username = request.POST.get("user_name")
    password = request.POST.get("pwd")
    email = request.POST.get("email")
    allow = request.POST.get("allow")
    # 判断用户传递过来的数据是否存在，不存在返回错误信息提示
    if not all([username,password,email]):
        return render(request,'register.html',{'error_msg':'数据不完整'})
    # 判断用户填写的邮箱是否为正确邮箱
    if not re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", email):
        return render(request,'register.html',{'error_msg':'邮箱格式不正确'})
    # 判断用户注册时是否勾选同意，同意后该字段POST请求参数为on
    if allow !='on':
        return render(request,'register.html',{'error_msg':'请勾选同意'})
    # user=User.objects._create_user(username,email,password)
    # 在进行用户注册之前，需要判断用户注册的用户名是否存在
    try:
        user=User.objects.get(username=username)
    except User.DoesNotExist:
        '如果出现该异常说明用户不存在,让user对象为空'
        user=None
    if user:
        return render(request,'register.html',{'error_msg':'用户已存在'})
    return redirect(reverse('goods:index'))
'''
# 发短信
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from django.core.cache import cache
from . import restful
import random
#缓存cache模块
from django.core.cache import cache
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
#图文
from .forms import RegisterForm
import json
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from  django.http import  JsonResponse

# 在df_user/views视图中定义RegisterView视图类在这个类中定义注册所需的
# get方法以及post方法，这个方法名必须等同于请求方式名
class RegisterView(View):
    '注册'
    def get(self,request):
        '显示注册界面'
        return render(request,'register.html')
    def post(self,request):
        '处理用户注册数据'
        # 加密用户id，生成激活的token
        # 提前导入：from e_shop import  settings
        username = request.POST.get("user_name")
        password = request.POST.get("pwd")
        email = request.POST.get("email")
        allow = request.POST.get("allow")
        # 判断用户传递过来的数据是否存在，不存在返回错误信息提示
        if not all([username, password, email]):
            return render(request, 'register.html',{'error_msg': '数据不完整'})
        # 判断用户填写的邮箱是否为正确邮箱
        if not re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$",email):
            return render(request, 'register.html', {'error_msg': '邮箱格式不正确'})
        # 判断用户注册时是否勾选同意，同意后该字段POST请求参数为on
        if allow != 'on':
            return render(request, 'register.html', {'error_msg': '请勾选同意'})
        # user=User.objects._create_user(username,email,password)
        # 在进行用户注册之前，需要判断用户注册的用户名是否存在
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            '如果出现该异常说明用户不存在,让user对象为空'
            user = None
        if user:
            return render(request, 'register.html', {'error_msg': '用户已存在'})
        user=User.objects.create_user(username,email,password)
        user.is_active=0
        user.save()
        serializer = Serializer(settings.SECRET_KEY,3600)  # 有效时间1小时
        info = {'confirm': user.id}
        token = serializer.dumps(info).decode() #解码
        # subject='海马生鲜欢迎你' #邮件标题
        # message='how are you '  #邮件正文
        # sender=settings.EMAIL_FROM    #发件人
        # receiver=[email]  #收件人
        # html_message = """
        #      <h1>%s 恭喜您成为海马生鲜注册会员</h1><br/><h3>请您在1小时内点击以下链接进行账户激
        # 活</h3><a
        # href="http://127.0.0.1:8000/df_user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
        # """ % (username, token, token)
        # send_mail(subject,message,sender,receiver,html_message=html_message)
        serializer = TJWSS(settings.SECRET_KEY,3600)
        info = {'confirm': user.id}
        token = serializer.dumps(info).decode('utf-8')
        send_active_email.delay(email, username,token)
        print('开始验证短信.........')
        phone=request.POST.get('phone')
        code=request.POST.get('code')
        cache_code=cache.get(phone)
        if code==cache_code:
            return redirect(reverse('goods:index'))
        else:
            return render(request,'register.html',{'error_msg': '验证码输入错误'})
class ActiveView(View):
    '账户激活'
    def get(self,request,token):
        #进行用户激活
        serializer=Serializer(settings.SECRET_KEY,3600)
        try:
            info=serializer.loads(token)
            #获取用户id
            # user_id=info['confirm']
            user_id=info.get('confirm')
            #根据用户id,获取用户对象
            user=User.objects.get(id=user_id)
            #设置该影虎字段对象中的is_active字段的值为1
            user.is_active=1
            user.save()
            #使用法相解析跳转到登录界面
            return redirect(reverse('user:login'))
        except SignatureExpired as e:
            '出现异常表示连接失效'
            return HttpResponse('激活链接已过期')
 # 创建LoginView类并在这个类中定义get方法用于显示登录页
class LoginView(View):
    '登录校验'
    def get(self,request):
        hashkey = CaptchaStore.generate_key()
        image_url = captcha_image_url(hashkey)
        register_form = RegisterForm()
        if 'username'in request.COOKIES:
            username=request.COOKIES.get('username')
            checked='checked'
        else:
            username=''
            checked=''
        hashkey = CaptchaStore.generate_key()
        image_url = captcha_image_url(hashkey)
        #生成表单验证码
        return render(request,'login.html',locals())

    # 在类视图LoginView中定义post函数
    def post(self,request):
        # 接收用户填写的数据
        username=request.POST.get('username')
        password=request.POST.get('pwd')
        # 校验参数完整性
        if not all([username,password]):
            return render(request,'login.html',{'error_msg':'数据不完整'})
        user=authenticate(username=username,password=password)
        # 正确返回user对象，不正确返回None
        if user is not None:
            # 用户名密码正确
            if user.is_active:
                #用户已激活
                #将用户成功状态保存在session,使用django认证系统中的login方法
                login(request,user)
                response=redirect(reverse('goods:index'))
                #判断用户是否购机用户名
                remember=request.POST.get('remember')
                if remember=='on':
                    # 表示勾选了,将用户名保存在cookie中
                    response.set_cookie('username',username,max_age=7*24*3600)
                else:
                    #删除cookie
                    response.delete_cookie('username')
                # 重定向到主页
                print('开始验证码————————————————')
                code = request.POST.get('code')
                print(code)
                get_captcha = CaptchaStore.objects.get(hashkey=request.POST.get('hashkey'))
                print('code', get_captcha)
                # return  render(request,'send_message.html',{'register_form':register_form})
                # return render(request, 'send_message.html', locals())
                if get_captcha.response == code.lower():
                    return response
                #重定向到主页
            else:
                return render(request,'login.html',{'error_msg':'账户未激活'})
        else:
            #用户名或者密码错误
            return render(request,'login.html',{'error_msg':'用户名或密码错误'})


#发短信
def send_sms(phone, code):
    # 这是阿里云短信接口密钥
    client = AcsClient('LTAIEx3Gbdbceg2C', 'MsCoWUm3x2iXaIcvtqhQLi9yj6nHxX', 'cn-hangzhou')
    code = "{'code':%s}" % (code)
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')
    request.add_query_param('RegionId', 'cn-hangzhou')
    request.add_query_param('PhoneNumbers', phone)
    request.add_query_param('SignName', '北网实训组')
    request.add_query_param('TemplateCode', 'SMS_165745016')
    request.add_query_param('TemplateParam', code)
    response = client.do_action(request)
    print(str(response, encoding='utf-8'))
    return str(response, encoding='utf-8')
def get_code(n=6, alpha=True):
    s = ''  # 创建字符串变量,存储生成的验证码
    for i in range(n):  # 通过for循环控制验证码位数
        num = random.randint(0, 9)  # 生成随机数字0-9
        if alpha:  # 需要字母验证码,不用传参,如果不需要字母的,关键字alpha=False
            upper_alpha = chr(random.randint(65, 90))
            lower_alpha = chr(random.randint(97, 122))
            num = random.choice([num, upper_alpha, lower_alpha])
        s = s + str(num)
    return s
def sms_send(request):
    phone=request.GET.get('phone')
    code=get_code(6,False)
    cache.set(phone,code,30*60)
    print('判断缓存中是否有，',cache.has_key(phone))
    print('获取Redis的验证码',cache.get(phone))
    print('----------------------------')
    print(phone)
    print(type(phone))
    print('------------------------------')
    result = send_sms(phone, code)
    return HttpResponse(result)
def sms_check(request):
    phone=request.GET.get('phone')
    code=request.GET.get('code')
    print('缓存中是否包含:',cache.has_key(phone))
    print('取值:',cache.get(phone))
    cache_code = cache.get(phone)
    if cache_code == code:
        print('ok')
        # return HttpResponse(json.dumps({'result':'OK'}))
        return restful.ok('OK',data=None)
    else:
        print('no')
        # return HttpResponse(json.dumps({'result':'False'}))
        return restful.params_error('验证码错误',data=None)
# 图文
def img_refresh(request):
    if not request.is_ajax():
        return HttpResponse('不是ajax请求')
    print('___________123__________________')
    new_key=CaptchaStore.generate_key()
    print('new_key',new_key)
    to_json_response={
        'hashkey':new_key,
        'image_url':captcha_image_url(new_key),
        }
    print(to_json_response['image_url'])
    return HttpResponse(json.dumps(to_json_response))
def img_check(request):
    print('验证用户输入的图片验证码')
    if request.is_ajax():
        cs=CaptchaStore.objects.filter(response=request.GET.get('code'),hashkey=request.GET.get('hashkey'))
        print(cs)
        if cs:
            json_data={'status':1}
        else:
            json_data={'status':0}
        return JsonResponse(json_data)
    else:
        json_data={'status':0}
        return JsonResponse(json_data)
